import React, { useState, useEffect, useRef } from 'react';
import { Button, Space, Pagination, message, Form, Input, DatePicker, Select, Modal, List } from 'antd';
import { DownloadOutlined, CopyOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import DraggableTable from '@/components/DraggableTable';
import { restoreColumns, saveColumns, getSortState } from '@/utils/columnStorage';
import './OrderDownload.css';

const OrderDownload: React.FC = () => {
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [tableData, setTableData] = useState<any[]>([]);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);
  const [currentOrder, setCurrentOrder] = useState<any>(null);
  const [modalLoading, setModalLoading] = useState(false);
  const [modalCurrent, setModalCurrent] = useState(1);
  const [modalPageSize, setModalPageSize] = useState(20);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState(false);
  // 排序状态
  const [sortState, setSortState] = useState({ field: null, order: null });
  const [columns, setColumns] = useState<any[]>([]);

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 订单状态选项
  const ORDER_STATUS = [
    { value: 2, label: '处理中' },
    { value: 1, label: '已完成' },
    { value: 0, label: '失败' }
  ];

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 89;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body') as HTMLElement;
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  // 获取订单列表数据
  const fetchOrderData = async () => {
    setTableLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const response = await request.get('/Management/DownloadOrderList', {
        params: {
          page: current,
          page_size: pageSize,
          order_name: formValues.order_name,
          status: formValues.status,
          create_time__gte: formValues.create_time_range?.[0]?.format('YYYY-MM-DD 00:00:00'),
          create_time__lte: formValues.create_time_range?.[1]?.format('YYYY-MM-DD 23:59:59')
        }
      });

      if (response.status === 200) {
        const { list, count, page } = response.data.data;
        const formattedData = list.map((item: any) => ({
          key: item.id,
          orderName: item.order_name,
          status: item.status,
          createTime: item.create_time,
          updateTime: item.update_time,
          fileCount: item.file_count,
          outputDir: item.output_dir,
          user_name: item.user_name,
          errorMessage: item.error_message
        }));

        setTableData(formattedData);
        setTotal(count);
		setCurrent(page);
      }
    } catch (error) {
      message.error('获取订单列表失败');
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    (request as any).initToken();
    // 初始化列配置，从localStorage恢复
    const tableKey = 'order_download_table';
    setColumns(restoreColumns(initialColumns, tableKey));
    
    // 恢复排序状态
    const savedSortState = getSortState(tableKey);
    if (savedSortState) {
      setSortState(savedSortState);
    }
  }, []);

  // 监听分页变化，重新获取数据
  useEffect(() => {
    fetchOrderData();
  }, [current, pageSize]);

  // 保存列配置到localStorage
  useEffect(() => {
    if (columns.length > 0) {
      const tableKey = 'order_download_table';
      saveColumns(columns, tableKey, sortState);
    }
  }, [columns, sortState]);

  // 计算表格滚动高度并监听窗口大小变化
  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 筛选表单提交
  const onFinish = (values: any) => {
    setCurrent(1); // 重置到第一页
    fetchOrderData();
  };

  // 下载订单
  const handleDownload = async (record: any) => {
    if (record.status !== '已完成') {
      message.warning('订单未完成，无法下载');
      return;
    }

    setModalLoading(true);
    setIsModalVisible(true);
    setCurrentOrder(record);

    try {
      const response = await request.post('/Management/DownloadOrderResultUrl', {
        order_id: record.key
      });

      if (response.status === 200) {
        setFileList(response.data.data.order_files_url);
      }
    } catch (error) {
      message.error('获取文件列表失败');
      setIsModalVisible(false);
    } finally {
      setModalLoading(false);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setFileList([]);
    setCurrentOrder(null);
  };

  const handleFileDownload = (url: string) => {
    window.open(url, '_blank');
  };

  const copyToClipboard = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;

    // 防止在页面上造成影响
    textArea.style.position = 'fixed';
    textArea.style.top = '-9999px';
    textArea.style.left = '-9999px';

    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        message.success('链接已复制到剪贴板');
      } else {
        message.error('复制失败，请手动复制');
      }
    } catch (err) {
      message.error('复制失败，请手动复制');
    }

    document.body.removeChild(textArea);
  };

  const handleCopyLink = (url: string) => {
    copyToClipboard(url);
  };

  // 删除订单
  const handleDelete = async (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除订单"${record.orderName}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request.post('/Management/DownloadOrderDelete', {
            order_ids: [record.key]
          });

          if (response.status === 200) {
            message.success('删除成功');
            fetchOrderData(); // 刷新列表
          }
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 批量删除订单
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的订单');
      return;
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个订单吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setBatchDeleteLoading(true);
        try {
          const response = await request.post('/Management/DownloadOrderDelete', {
            order_ids: selectedRowKeys
          });

          if (response.status === 200) {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            fetchOrderData(); // 刷新列表
          }
        } catch (error) {
          message.error('批量删除失败');
        } finally {
          setBatchDeleteLoading(false);
        }
      }
    });
  };

  // 表格选择配置
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    }
  };

  // 处理列变化
  const handleColumnsChange = (newColumns: any[]) => {
    setColumns(newColumns);
  };

  // 表格列定义
  const initialColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      align: 'center' as const,
      render: (_: any, __: any, idx: number) => idx + 1 + (current - 1) * pageSize
    },
    {
      title: '订单名称',
      dataIndex: 'orderName',
      key: 'orderName',
      width: 250
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100
    },
    {
      title: '文件数量',
      dataIndex: 'fileCount',
      key: 'fileCount',
      width: 100
    },
    {
      title: '输出目录',
      dataIndex: 'outputDir',
      key: 'outputDir',
      width: 200,
      render: (text: string) => (
        <Button type="link" onClick={() => copyToClipboard(text)} style={{ padding: 0, height: 'auto' }}>
          {text}
        </Button>
      )
    },
    {
      title: '创建人',
      dataIndex: 'user_name',
      key: 'user_name',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right' as const,
      align: 'center' as const,
      render: (_: unknown, record: any) => (
        <Space>
          <Button
            size="small"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
            loading={downloadLoading}
            disabled={record.status !== '已完成'}>
            下载
          </Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div className="order-download-container">
      <div style={{ position: 'absolute', width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div className="breadcrumb">
          <Button 
            type="link" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => window.history.back()}
            style={{ padding: 0, marginRight: 10 }}
          >
            返回
          </Button>
          订单管理 &gt; 订单下载
        </div>
        <div className="content" style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* 筛选表单 */}
          <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            {/* 订单ID输入框 */}
            <Form.Item name="order_name" label="订单ID" style={{ width: 320 }}>
              <Input placeholder="请输入订单ID" />
            </Form.Item>

            {/* 创建时间范围选择器 */}
            <Form.Item label="创建时间" style={{ width: 320 }} name="create_time_range">
              <DatePicker.RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
            </Form.Item>

            {/* 订单状态选择器 */}
            <Form.Item name="status" label="订单状态" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择订单状态" style={{ width: '100%' }}>
                {ORDER_STATUS.map((status) => (
                  <Select.Option key={status.value} value={status.value}>
                    {status.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item style={{ paddingLeft: 80, width: 320 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  筛选
                </Button>
                <Button
                  htmlType="button"
                  onClick={() => {
                    form.resetFields();
                    fetchOrderData();
                  }}>
                  清除
                </Button>
              </Space>
            </Form.Item>
          </Form>

          {/* 数据表格 */}
          <div className="order-table-container" ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
            <DraggableTable
              columns={columns}
              onColumnsChange={handleColumnsChange}
              rowSelection={rowSelection}
              dataSource={tableData}
              pagination={false}
              scroll={{ y: tableScrollY, x: 'max-content' }}
              bordered
              size="small"
              loading={tableLoading}
              rowClassName={(_: any, index: number) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
              onChange={(pagination, filters, sorter) => {
                if (sorter.field) {
                  const newSortState = {
                    field: sorter.field,
                    order: sorter.order
                  };
                  setSortState(newSortState);
                }
              }}
              footer={() => (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Button
                    type="primary"
                    danger
                    onClick={handleBatchDelete}
                    loading={batchDeleteLoading}
                    disabled={selectedRowKeys.length === 0}>
                    批量删除
                  </Button>
                  <Pagination
                    current={current}
                    pageSize={pageSize}
                    total={total}
                    showSizeChanger={true}
                    pageSizeOptions={['10', '20', '50']}
                    onChange={(page, size) => {
                      setCurrent(page);
                      setPageSize(size!);
                    }}
                    showTotal={(total) => `共 ${total} 条`}
                    size="small"
                  />
                </div>
              )}
            />
          </div>
        </div>
      </div>

      <Modal
        title={`订单文件列表 - ${currentOrder?.orderName || ''}`}
        open={isModalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width={800}>
        <div className="file-list-container">
          <List
            loading={modalLoading}
            dataSource={fileList.slice((modalCurrent - 1) * modalPageSize, modalCurrent * modalPageSize)}
            pagination={{
              current: modalCurrent,
              pageSize: modalPageSize,
              total: fileList.length,
              onChange: (page, pageSize) => {
                setModalCurrent(page);
                setModalPageSize(pageSize);
              },
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              showTotal: (total) => `共 ${total} 条`
            }}
            renderItem={(item) => (
              <List.Item
                actions={[
                  <Button
                    type="link"
                    onClick={() => handleFileDownload((request as any).getUrl(`/Management/Download?download_file_id=${item.files_id}`))}
                    icon={<DownloadOutlined />}>
                    下载
                  </Button>,
                  <Button
                    type="link"
                    onClick={() =>
                      handleCopyLink((request as any).getUrl(`/Management/Download?data_type=${item.data_type}&product_id=${item.product_id}`))
                    }
                    icon={<CopyOutlined />}>
                    复制链接
                  </Button>
                ]}>
                <List.Item.Meta title={item.url} />
              </List.Item>
            )}
          />
        </div>
      </Modal>
    </div>
  );
};

export default OrderDownload;